import os
from win32com import client
from pathlib import Path
import signal


def get_path(url=""):
    if url:
        path = url
    else:
        # 获取当前运行路径
        path = input("请输入需要转换PDF的文件地址(当前目录直接回车即可)：")
        if not path:
            path = os.getcwd()
        # path = r'C:\Users\admin\Desktop\网盘\文章'

    # 是否有这个路径
    # if not os.path.exists(path):        # 创建路径
    #     os.makedirs(path)

    # print(path)
    # 获取所有文件名的列表
    filename_list = os.listdir(path)
    # 获取所有word文件名列表
    wordname_list = [filename for filename in filename_list
                     if filename.endswith((".doc", ".docx"))]
    # 是否有这个路径
    if os.path.exists(path) and not os.path.exists(path+'/pdf') and int(len(wordname_list)) > 0:  # 创建路径
        os.makedirs(path+'/pdf')

    for file in os.listdir(path):
        file_path = os.path.join(path, file)

        if os.path.isdir(file_path):
            convert_word_to_pdf(file_path)

    for wordname in wordname_list:
        # 分离word文件名称和后缀，转化pdf名称
        pdfname = os.path.splitext(wordname)[0] + '.pdf'
        # 拼接 路径和文件名
        wordpath = os.path.join(path, wordname)
        pdfpath = os.path.join(path+'/pdf', pdfname)
        my_file = Path(path+'/pdf/'+pdfname)
        if my_file.is_file():
            print('【无需转换】——'+wordpath+"【已存在】")
            continue
        # 生成器
        print(my_file)
        yield wordpath, pdfpath,


def convert_word_to_pdf(url=""):
    word =  client.DispatchEx("Word.Application")
    word.Visible = 0
    for wordpath, pdfpath in get_path(url):
        # newpdf = word.Documents.Open(wordpath)
        # newpdf.SaveAs(pdfpath, FileFormat=17)
        # newpdf.Close()
        worddoc = word.Documents.Open(wordpath,ReadOnly = 1)
        worddoc.SaveAs(pdfpath, FileFormat = 17)
        print('【转换成功】——'+pdfpath)
        worddoc.Close()

    # ppt转化为pdf
    # ppt = comtypes.client.CreateObject("Powerpoint.Application")
    # ppt.Visible = 1
    # newpdf = ppt.Presentations.Open(in_file)
    # newpdf.SaveAs(out_file, FileFormat=32)
    # newpdf.Close()


# if __name__ == "__main__":
convert_word_to_pdf()
